<?php


class DC extends Doctrine_Collection
{
    /**
     * Load all relationships or the named relationship passed
     *
     * @param mixed $name
     * @return boolean
     */
    public function loadRelated($name = null, $property = false, $condition = null)
    {
        $list = array();
        $query   = new Doctrine_Query($this->_table->getConnection());

        if ( ! isset($name)) {
            if (empty($list)) {
                foreach ($this->data as $record) {
                    $value = $record->getIncremented();
                    if ($value !== null
                        && (empty($property) || $record->$poperty === $condition)
                    ) {
                        $list[] = $value;
                    }
                }
            }

            $query->from($this->_table->getComponentName());
            if (!empty($list)) {
                $query->where($this->_table->getComponentName() . '.id IN (' . substr(str_repeat("?, ", count($list)),0,-2) . ')', $list);
            }

            return $query;
        }

        $rel     = $this->_table->getRelation($name);

        if (empty($list)) {
            if ($rel instanceof Doctrine_Relation_LocalKey || $rel instanceof Doctrine_Relation_ForeignKey) {
                foreach ($this->data as $record) {
                    if (empty($property) || $record->$property === $condition) {
                        $list[] = $record[$rel->getLocal()];
                    }
                }
            } else {
                foreach ($this->data as $record) {
                    $value = $record->getIncremented();
                    if ($value !== null
                        && (empty($property) || $record->$property === $condition)
                    ) {
                        $list[] = $value;
                    }
                }
            }
        }

        if (empty($list)) {
            return;
        }

        $dql     = $rel->getRelationDql(count($list), 'collection');
        $coll    = $query->query($dql, $list);

        $this->populateRelated($name, $coll);
    }
}
